window.onerror = function (message, url, line, column, error) {
	// 关闭等待
	WeKnow.closeLoading();

	console.log('错误被捕获了::::', message, url, '行：'+line, '列：'+column, "错误信息："+error);

	var param = {
		message:message,
		url:url,
		line:line,
		column:column
	}

	$.ajax({
		type: "POST",
		url:WeKnow.getRealPath()+"/sendJsError.do",
		dataType: "json",
		contentType: "application/json",
		data: JSON.stringify(param),
		success:function(data) {
			console.log("通知成功");
		},
		error: function() {
			console.log("通知失败");
		}
	});


}

!function() { // 扩展js对象
	//时间格式
	Date.prototype.format = function(format) {
	    var o =
	    {
	        "M+" : this.getMonth()+1, //month
	        "d+" : this.getDate(),    //day
	        "h+" : this.getHours(),   //hour
	        "m+" : this.getMinutes(), //minute
	        "s+" : this.getSeconds(), //second
	        "q+" : Math.floor((this.getMonth()+3)/3),  //quarter
	        "S" : this.getMilliseconds() //millisecond
	    }
	    if(/(y+)/.test(format))
	    format=format.replace(RegExp.$1,(this.getFullYear()+"").substr(4 - RegExp.$1.length));
	    for(var k in o)
	    if(new RegExp("("+ k +")").test(format))
	    format = format.replace(RegExp.$1,RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));
	    return format;
	}
	
	String.prototype.format = function() {  // alert("js实现用自符串替换占位符{0} {1} {2}".format("I", "LOVE", "YOU"));  
	  if(arguments.length==0) return this;  
	  for(var s=this, i=0; i<arguments.length; i++)  
	    s=s.replace(new RegExp("\\{"+i+"\\}","g"), arguments[i]);  
	  return s;  
	};
	
	// 日期字符串转换成 yyyy-MM-dd
	String.prototype.dateFormart= function() {
		var _this = this;
		if (_this.length) {
			if (MY_VALIDATOR.isDate(_this, 'yyyyMMdd') ||
				MY_VALIDATOR.isDate(_this, 'yyyy-MM-dd') ||
				MY_VALIDATOR.isDate(_this, 'yyyy.MM.dd') ||
				MY_VALIDATOR.isDate(_this, 'yyyy/MM/dd')) {
				
				if (_this.length == 8) {
					var y = _this.substring(0, 4);
					var m = _this.substring(4, 6);
					var d = _this.substring(6, 8);
					return y + '-' + m + '-' + d;
				} else if (_this.length == 10) {
					var y = _this.substring(0, 4);
					var m = _this.substring(5, 7);
					var d = _this.substring(8, 10);
					return y + '-' + m + '-' + d;
				}
			}
			return _this;
		}
		
		return '';
	}
}();

/**
 * weknow core api
 */
var WeKnow = (function() {
	
	function uuid() {
		var s = [];
		var hexDigits = "0123456789abcdef";
		for (var i = 0; i < 36; i++) {
		    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
		}
		s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
		s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
		s[8] = s[13] = s[18] = s[23] = "-";
		 
		var uuid = s.join("");
		return uuid;
	}
	
	/**
	 * private function
	 */
	function hashCode(input) {
		var I64BIT_TABLE =
			'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-'.split('');
		return function(input) {
			var hash = 5381;
			var i = input.length - 1;
			if(typeof input == 'string'){
				for (; i > -1; i--)
					hash += (hash << 5) + input.charCodeAt(i);
			}
			else{
				for (; i > -1; i--)
					hash += (hash << 5) + input[i];
				}
			var value = hash & 0x7FFFFFFF;
			var retValue = '';
			do {
				retValue += I64BIT_TABLE[value & 0x3F];
			}
			while(value >>= 6);
			return retValue;
		}(input);
	}

	/**
	 * public funciton
	 */
	function getRealPath() {
		//获取当前网址，如： http://localhost:8083/myproj/view/my.jsp
	  	var curWwwPath = window.document.location.href;
	  	//获取主机地址之后的目录，如： myproj/view/my.jsp
	  	var pathName = window.document.location.pathname;
	  	
		//获取主机地址，如： http://localhost:8083
		var pos = curWwwPath.indexOf(pathName);
	  	var localhostPath = curWwwPath.substring(0,pos);
	  	
		//获取带"/"的项目名，如：/myproj
		var projectName = pathName.substring(0,pathName.substr(1).indexOf('/')+1);
	  	
		//得到了 http://localhost:8083/myproj
		
		/***
		 * 生产环境中 url 没有项目名称（2dEnterpriseManage），特此做如下讨巧处理
		 */
		if (localhostPath.indexOf('www') > -1 || localhostPath.indexOf('dev') > -1 || localhostPath.indexOf('aioclinic.com') > -1) { // 生产环境
			return localhostPath;
		} else { // 开发环境
			return localhostPath + projectName;
		}
	}
	
	function include(file) {
		var files = typeof file == "string" ? [file] : file;
		for (var i = 0; i < files.length; i++) {
			var name = files[i].replace(/^\s|\s$/g, ""); 
			var att = name.split('.'); 
			var ext = att[att.length - 1].toLowerCase(); 
			var isCSS = ext == "css"; 
			var tag = isCSS ? "link" : "script"; 
			var attr = isCSS ? " type='text/css' rel='stylesheet' " : " type='text/javascript' "; 
			var link = (isCSS ? "href" : "src") + "='" + getRealPath() + name + "?V1.0'";
			if ($(tag + "[" + link + "]").length == 0) $("head").prepend("<" + tag + attr + link + "></" + tag + ">");
		} 
	} 
	
	// 交换dom元素
	function swap($dom1, $dom2) {
		var $temobj1 = $("<div></div>");
	    var $temobj2 = $("<div></div>");
	    $temobj1.insertBefore($dom1);
	    $temobj2.insertBefore($dom2);
	    $dom1.insertAfter($temobj2);
	    $dom2.insertAfter($temobj1);
	    $temobj1.remove();
	    $temobj2.remove();
	}
	
	function scrollTo(domId, offset, f) {
		$("html, body").animate(
			{
			  scrollTop: ($(domId).offset().top + offset) + "px"
			},
			'slow',
			'swing',
			f
		);
	}
	
	/**
	 * 页面submit post
	 */
	function submit(action, params) {
		loading({opacity: 0.5});
		var form = document.createElement("form");   
	    document.body.appendChild(form);
	  	form.method = 'POST';
		form.action = action;
		for(key in params) {
			var input = document.createElement("input");
			input.type = "hidden"; 
		  	input.name = key; 
		  	input.value = params[key];
			form.appendChild(input);
		}
	    form.submit();
	}
	
	function makeUrl(url, params) {
		if (!$.isEmptyObject(params)) {
			var firstParam = true;
			for(key in params) {
				if (firstParam && url.indexOf('?') == -1) {
					url += "?";
				} else {
					url += "&";
				}
				url += key + "=" + params[key];
				firstParam = false;
			}
		}
		return url;
	}
	/**
	 * 页面迁移 get
	 * @param url
	 */
	function location(url, params) {
		loading({opacity: 0.5});
		if (!$.isEmptyObject(params)) {
			var firstParam = true;
			for(key in params) {
				if (firstParam && url.indexOf('?') == -1) {
					url += "?";
				} else {
					url += "&";
				}
				url += key + "=" + params[key];
				firstParam = false;
			}
		}
		window.location.href=url;
	}
	
	/**
	 * 打开新窗口
	 */
	function newWindow(url, width, height) {
		var h = ("undefined" == typeof(height)) ? (window.screen.height * 80 / 100) : height;
		var w = ("undefined" == typeof(width)) ? (window.screen.width * 80 / 100) : width;
		var left = (window.screen.width - w) / 2;
		var top = 0;
		var params = "toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no";
		params += ",height=" + h + ",width=" + w + ",left=" + left + ",top=" + top;
		if (url.indexOf("?") > -1) {
			url += "&isSubWindow=true";
		} else {
			url += "?isSubWindow=true";
		}
		var newWin = window.open(url, hashCode(url), params);
		if (newWin) newWin.focus();
		return newWin;
	}
	function newMaxWindow(url) {
		var newWin = window.open(url, hashCode(url));
		if (newWin) newWin.focus();
		return newWin;
	}
	
//	/**
//	 * 模态加载
//	 * @param url
//	 */
//	function openModalPage(url, options) {
//		var modalDialogSize = '';
//		if (options && options.modal-dialog-size) {
//			modalDialogSize = options.modal-dialog-size;
//		}
//		var e = '';
//		e += '<div class="modal fade" tabindex="-1" role="dialog">';
//			e += '<div class="modal-dialog ' + modalDialogSize + '" role="document">';
//				e += '<div class="modal-content">';
//				e += '</div>';
//			e += '</div>';
//		e += '</div>';
//		var $modal = $(e).appendTo($('body')).modal({
//			remote: url,
//			keyboard: true
//		}).on('hidden.bs.modal', function (event) {
//			$(this).remove();
//		});
//		return $modal;
//	}
	
	/**
	 * 显示加载中
	 */
	function loading(options) {
		var opacity = 0.5;// default
		if ('undefined' != typeof options && options.opacity != null) opacity = options.opacity;
		var $animationload = $('body div.animationload');
		if ($animationload.length) {
			$animationload.css('opacity', opacity).show().find('div.loader').show();
		} else {
			$('<div class="animationload" style="opacity: ' + (opacity ? opacity : 1) + ';"><div class="loader"></div></div>').appendTo('body');
		}
	}
	/**
	 * 取消显示加载中
	 */
	function closeLoading(speed) {
		var $animationload = $('body div.animationload');
		if ($animationload.length) {
			$animationload.find('div.loader').delay(('undefined' != typeof speed && speed === 'slow' ? 25 : 0)).fadeOut();
			$animationload.delay(('undefined' != typeof speed && speed === 'slow' ? 50 : 0)).fadeOut("slow");
		}
	}
	
//	/**
//	 * 弹出框显示消息(提醒) 右上
//	 */
//	function notify(message, style) {
//		if ('undefined' == typeof style || (style !== 'success' && style !== 'error')) style = 'white';
//		$.Notification.notify(
//			style,
//			'top right',
//			'',
//			message
//		);
//	}
//	function autoHideNotify(message, style) {
//		if ('undefined' == typeof style || (style !== 'success' && style !== 'error')) style = 'white';
//		$.Notification.autoHideNotify(
//			style,
//			'top right',
//			'',
//			message
//		);
//	}
	function alertMsg(msg, fun) {
		if(typeof fun === "function") {
			layer.alert(msg, {closeBtn: 0}, fun);
		} else {
			layer.alert(msg, {closeBtn: 0});
		}
	}
	
	function layerMsg(msg, options) {
		if ('undefined' != typeof msg && msg != null) {
			var msgLength = msg.length;
			if ('undefined' === typeof msg || !msgLength) return;
			if (msgLength < 10) {
				if (!('time' in options)) options.time = 1500;
			} else if (msgLength < 20) {
				if (!('time' in options)) options.time = 2500;
			} else {
				if (!('time' in options)) options.time = 5000;
			}
			layer.msg(msg, options);
		}
	}
	function successMsg(msg, options) {
		if ('undefined' === typeof options) options = {};
		options.icon = 1;
		layerMsg(msg, options);
	}
	
	function errorMsg(msg, options) {
		if ('undefined' === typeof options) options = {};
		options.icon = 2;
		layerMsg(msg, options);
	}
	
	function notifyMsg(msg, options) {
		if ('undefined' === typeof options) options = {};
		options.icon = 7;
		layerMsg(msg, options);
	}
	
	function systemMsg(msg, options) {
		if ('undefined' === typeof options) options = {};
		options.icon = 7;
		options.time = 10000;
		try {
            throw new Error();
        } catch (e) {
            var loc = e.stack.replace(/Error\n/).split(/\n/)[1].replace(/^\s+|\s+$/, "");
            msg += '<br>' + loc;
        }
		layerMsg(msg, options);
	}
	
	/**
	 * modal
	 */
	function modal(params) {
		if ('undefined' !== typeof params) {
			
			var $modal = $('div.md-modal.confirm');
			if ($modal.length) { // 已经存在的话，删除重建
				$modal.remove();
			}
			
			var txt = '';
			txt += '<div class="md-modal md-effect-1 confirm">';
				txt += '<div class="md-content">';
				if ('undefined' !== typeof params.title && params.title.length) {
					txt += '<div class="modal-header">';
						txt += '<h4 class="modal-title text-center">' + params.title + '</h4>';
					txt += '</div>';
				}
					txt += '<div class="modal-body">';
						if ('undefined' !== typeof params.message) {
							txt += params.message;
						}
		            txt += '</div>';
					txt += '<div class="modal-footer"></div>';
				txt += '</div>';
			txt += '</div>';
			txt += '<div class="md-overlay"></div>';//<!-- the overlay element -->
			
			$modal = $(txt).appendTo($("body"));
			
			if ('undefined' === typeof params.buttons || !params.buttons.length) {
				$modal.find("div.modal-footer").remove();
			} else {
				$.each(params.buttons, function(idx, btn) {
					var bTxt = '<button type="button" class="btn ' + btn.class + '">' + btn.name + '</button>';
					$(bTxt).appendTo($modal.find("div.modal-footer")).on("click", btn.onClick)
				});
			}
			
			$modal.addClass("md-show");
			$('body').on('click', '.md-close', function() {
				closeModal();
			});
			return $modal;
		}
	}
	function closeModal() {
		var $modal = $('div.md-modal.confirm');
		if ($modal.length) {
			$modal.remove();
			$('div.md-overlay').remove();
		}
	}
	/**
	 * 确认dialog
	 */
	function confirm(message, callbackOK) {
		modal(
			{
				title: '确认',
				message: message,
				buttons:[
					{name:'取消', class:'btn md-close btn-default'},
			        {name:'确认', class:'btn btn-primary',
			        	onClick: function() {
			        		closeModal();
			        		if ('function' === typeof callbackOK) callbackOK();
			        	}
			        }
				]
			}
		);
	}
	
	/**
	 * 参数+url 组件新url
	 */
	function buildUrl(url, params) {
		if ('undefined' !== typeof params) {
			var firstParam = true;
			for(key in params) {
				if (firstParam && url.indexOf('?') == -1) {
					url += "?";
				} else {
					url += "&";
				}
				url += key + "=" + params[key];
				firstParam = false;
			}
		}
		return url;
	}
	
	/**
	 * 过滤ajax返回结果。主要check是否session过期
	 * @param data
	 */
	function filterAjaxResult(data) {
		if (typeof(data) != "undefined" && data != null) {
			var errorcode = data.errorcode;
			if (typeof(errorcode) != "undefined" && errorcode != null) {
				if (errorcode == -999) { // 超时等异常
					if (window.parent.timeout) {
						window.parent.timeout();
					} else {
						timeout();
					}
//					if (isYbNetwork()) {
//						WeKnow.submit(WeKnow.getRealPath() + "/vpn/login",  {timeout: true});
//					} else {
//						WeKnow.submit(WeKnow.getRealPath() + "/login",  {timeout: true});
//					}
					return false;
				}
			}
		}
		return true;
	}
	
	/**
	 * WeKnow tab page
	 */
	function renameTabPage(name) {
		if (window.parent) {
			window.parent.renameTab(name);
		} else {
			renameTab(name);
		}
	}
	function removeTabPage(title) {
		if (window.parent) {
			window.parent.removeTab(name);
		} else {
			renameTab(name);
		}
	}
	function openTabPage(name, url) {
		if (window.parent) {
			window.parent.openTab(name, url);
		} else {
			renameTab(name);
		}
	}
	function openTabPage2(userUUID, name, url) {
		if (window.parent) {
			window.parent.openTab2(userUUID, name, url);
		} else {
			renameTab(name);
		}
	}
	
	/**
	 * 退出
	 */
	function logout() {
		window.parent.logout();
	}
	
	function IEVersion() {
        var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串  
        var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; //判断是否IE<11浏览器  
        var isEdge = userAgent.indexOf("Edge") > -1 && !isIE; //判断是否IE的Edge浏览器  
        var isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf("rv:11.0") > -1;
        if(isIE) {
            var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
            reIE.test(userAgent);
            var fIEVersion = parseFloat(RegExp["$1"]);
            if(fIEVersion == 7) {
                return 7;
            } else if(fIEVersion == 8) {
                return 8;
            } else if(fIEVersion == 9) {
                return 9;
            } else if(fIEVersion == 10) {
                return 10;
            } else {
                return 6;//IE版本<=7
            }   
        } else if(isEdge) {
            return 'edge';//edge
        } else if(isIE11) {
            return 11; //IE11  
        }else{
            return -1;//不是ie浏览器
        }
    }
	
	/**
	 * 是否医保工作环境
	 */
	function isYbNetwork() {
		if (typeof myYiBaoConfig !== 'undefined') {
			return (myYiBaoConfig.getProvinceConfig() != null || myYiBaoConfig.getCityConfig() != null)/* && myYiBaoConfig.getVpnLogin() == '1'*/;
		}
		return false;
	}
	
	/**
	 * 是否医保测试
	 */
	function isYbTesting() {
		var isTesting = sessionStorage.getItem("YIBAO_TESTING");
		return typeof isTesting !== 'undefined' && isTesting == 'true';
	}
	function setYbTesting(isTesting) {
		if (typeof isTesting !== 'undefined' && isTesting) {
			sessionStorage.setItem("YIBAO_TESTING", isTesting);
		} else {
			sessionStorage.removeItem("YIBAO_TESTING");
		}
	}
	
	return {
		 include: include // 动态加载js、css文件
		,swap: swap // 交换dom元素位置
		,scrollTo: scrollTo // 移动位置
		,buildUrl: buildUrl // 组装url
		,filterAjaxResult: filterAjaxResult // 过滤ajax返回结果
		,newWindow: newWindow // 打开新窗口
		,newMaxWindow: newMaxWindow
		,getRealPath: getRealPath//绝对路径
		,uuid: uuid
		/**
		 * weknow tab page
		 */
		,renameTabPage: renameTabPage
		,removeTabPage: removeTabPage
		,openTabPage: openTabPage
		,openTabPage2: openTabPage2
		,logout: logout
		
		/**
		 * 页面提交
		 */
		,makeUrl: makeUrl
		,location: location // 页面跳转 GET
		,submit: submit // 页面跳转 POST
		/**
		 * 加载中
		 */
		,loading: loading // 加载中
		,closeLoading: closeLoading // 关闭加载中
		
		/**
		 * 消息提示
		 */
//		,notify: notify // 通知
//		,autoHideNotify: autoHideNotify // 通知，5s自动隐藏
		,errorMsg: errorMsg
		,successMsg: successMsg
		,notifyMsg: notifyMsg
		,systemMsg: systemMsg
		
		,alertMsg: alertMsg//点确定关闭
		
		/**
		 * 确认窗口
		 */
		,modal: modal // modal窗口
		,closeModal: closeModal // 关闭modal窗口
		,confirm: confirm // 确认modal窗口
		,IEVersion: IEVersion
		
		/**
		 * 医保相关
		 */
		,isYbNetwork: isYbNetwork // 是否医保工作环境
		,isYbTesting: isYbTesting
		,setYbTesting: setYbTesting
	}
})();


$(document).ready(function() {
	// 禁用右键、文本选择功能、复制按键
	$(document).bind("contextmenu",function(){return false;});
//	$(document).bind("selectstart",function(){return false;});
//	$(document).keydown(function(){return key(arguments[0])});
	
	// 动态加载
	// 通知plugins
//	WeKnow.include('/plugins/notifications/notification.css');
//	WeKnow.include('/plugins/notifyjs/dist/notify.min.js');
//	WeKnow.include('/plugins/notifications/notify-metro.js');
//	WeKnow.include('/plugins/notifications/notifications.js');
	WeKnow.include('/plugins/modal-effect/css/component.css');
	WeKnow.include('/plugins/modal-effect/js/classie.js');
	WeKnow.include('/plugins/modal-effect/js/modalEffects.js');

	WeKnow.include('/plugins/layer-v3.0.3/skin/default/layer.css');
	WeKnow.include('/plugins/layer-v3.0.3/layer.js');
	
	// 去掉所有input的autocomplete, 显示指定的除外
	$('input:not([autocomplete]),textarea:not([autocomplete]),select:not([autocomplete])').attr('autocomplete', 'off');
	
	// 取消loading
	WeKnow.closeLoading('slow');
	
	// enter key 跳转
	$('input, textarea').keydown(function (event) {
//		event.stopPropagation();
		var $that = $(this);
		switch (event.keyCode) {
	    	case 13: // Enter
		    	var $next = $($that.data('nextfocus'));
				if ($next.length) {
					$next.focus();
				}
				break;
		}
	});
});

